<template>
  <div v-loading="pageLoading" :class="{'mobile-create': showMobilePage}" class="issue-invoice-create-container">
    <explanation :explanation="explanationObj" is-expand style="margin: 0;"/>
    <div :class="{'pb55':device!=='mobile'}" class="page-container">
      <ApplicationInfo
        ref="applicationInfoRef"
        v-model="applicationInfo"
        @onSelectHistoryInvoice="onSelectHistoryInvoice"
      />
      <TaxpayerInfo ref="taxpayerRef" :show-mobile-page="showMobilePage" v-model="applicationInfo" :finance-data="financeData"/>
      <!-- <OrderInfo v-if="showOrderInfo" ref="orderInfoRef" /> -->
      <ReceiptInfo
        v-if="applicationInfo.isArrival"
        ref="receiptInfoRef"
        :table-data="financeData"
        :is-create="true"
        :issue-id="id"
        :application-info="applicationInfo"
        :tax-payer="applicationInfo.taxpayer"
        @fillTaxpayerInfo="fillTaxpayerInfo"
        @selectFinance="selectFinance"
        @handleDelete="handleDeleteReceipt"/>
      <ContractInfo
        v-if="showContractInfo"
        ref="contractInfoRef"
        :show-order-info="showOrderInfo"
      />
      <audit-process
        ref="auditProcess"
        :loading="loading"
        v-model="auditInfo"
        :old-audit-info="oldAuditInfo"
        :default-aduitor-list="[{id:applicationInfo.proposerId,userName:applicationInfo.proposer}]"

        :flow-structure="processDetail"
        :is-modify="Boolean(remodifyId)"
        :disable="Boolean(remodifyId)"
        :is-modify-form="Number(isModifyForm)"
        :current-process-index="Number(currentProcessIndex)"
        @submit="submit(SUBMITTYPE.SUBMIT,$event)"
        @getProcess="getProcess" />
      <fixed-pagination>
        <template v-if="showMobilePage">
          <el-dropdown trigger="click">
            <el-button class="el-dropdown-link search-btn-style more-btn">更多操作<i class="el-icon-caret-bottom"/></el-button>
            <el-dropdown-menu slot="dropdown" class="mobile-menu-invoice">
              <el-dropdown-item style="width:200px;text-align: center;font-size: 14px;">
                <el-checkbox v-model="applicationInfo.isRememberInfo">保存开票信息至该客户</el-checkbox>
              </el-dropdown-item>
              <el-dropdown-item v-if="(!remodifyId && !reapplyId) || createNew" style="width:200px;text-align: center;font-size: 14px;" @click.native="submit(SUBMITTYPE.DRAFT)">
                <div>保存草稿</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button size="small" type="primary" @click="openDrawer()">发起审批</el-button>
          <el-button class="cancel-btn-style" size="small" @click="toBack">返回</el-button>
        </template>
        <div v-else class="center bottom-btn-group">
          <div class="bottom-checkbox">
            <el-checkbox v-model="applicationInfo.isRememberInfo">保存开票信息至该客户</el-checkbox>
          </div>
          <el-button size="small" type="primary" @click="openDrawer()">发起审批</el-button>
          <el-button v-if="(!remodifyId && !reapplyId) || createNew" size="small" type="info" @click="submit(SUBMITTYPE.DRAFT)">保存草稿</el-button>
          <el-button class="cancel-btn-style" size="small" @click="toBack">返回</el-button>
        </div>
      </fixed-pagination>
    </div>
  </div>
</template>

<script>
// components
import ApplicationInfo from './module/applicationInfo';
import ContractInfo from './module/contractInfo';
import TaxpayerInfo from './module/taxpayerInfo';
import ReceiptInfo from './module/receiptInfo';
import AuditProcess from '@/components/Common/auditProcess';
import explanation from '@/components/Common/explanation';
// tool
import { mapState } from 'vuex';
import ElMessage from '@/utils/message';
import { createAuditStructure } from '@/utils/aduitor';
import { SUBMITTYPE } from '@/utils/const/cost';
import { isContained } from '@/utils/tools';
import processCreate from '@/mixins/processCreate';
import mobileCreate from '@/mixins/mobileCreate';
// api
import {
  formSubmitIssueInvoice,
  storeIssueInvoice,
  editIssueInvoice,
  getOrderRelationContract,
  getIssueInvoiceDetail
} from '@/api/issueInvoice';
import { processManagementDetail } from '@/api/legal';
import { showModal } from '@/utils/message';

export default {
  components: {
    ApplicationInfo,
    ContractInfo,
    AuditProcess,
    explanation,
    TaxpayerInfo,
    ReceiptInfo
  },
  mixins: [processCreate, mobileCreate],
  data() {
    return {
      id: '',
      SUBMITTYPE,
      applicationInfo: {
        proposerId: null, // 申请人
        proposer: null, // 申请人名字
        applyDepartmentId: null, // 申请部门
        businessType: 1, // 业务类型
        referenceId: '', // 引用历史
        ourTitle: '', // 我方抬头
        invoiceType: '', // 发票类型
        invoiceRequired: false,
        taxpayerId: null, // 纳税人id
        taxpayer: null, // 纳税人名称
        customType: null, // 纳税人类型
        taxpayerNum: '', // 纳税人识别号
        accountsBank: '', // 开户行
        issueAddress: '', // 开票地址
        accountNum: '', // 开户账号
        phone: '', // 注册电话
        certificateFile: [], // 一般纳税人证明
        email: '', // 发票接收邮箱
        project: '', // 开票项目
        amount: '', // 含税金额
        remark: '', // 备注
        attachment: [], // 附件
        isArrival: null, // 是否到账
        arrivalDate: '', // 预计到账日期
        arrivalFile: [], // 到账证明
        isExecution: null, // 执行情况
        isSign: null, // 合同情况
        isRememberInfo: true
      },
      showOrderInfo: true, // 是否显示订单信息
      showContractInfo: true, // 是否显示合同信息
      auditInfo: {
        activeTime: null,
        isSigner: 0,
        countersignSet: 0,
        process: [],
        senders: [],
        id: null
      }, // 流程信息
      processDetail: null,
      isEdit: false,
      remodifyId: null, // 修改，审批流程不能修改
      reapplyId: null, // 重新申请
      explanationObj: {
        content: '',
        styConfig: ''
      }, // 审批说明
      loading: false,
      oldAuditInfo: null, // 保存旧流程用于比较，修改的情况需要判断流程是否发生变动
      pageLoading: false,
      financeData: []
    };
  },
  computed: {
    ...mapState({
      'device': state => state.app.device,
      'userInfo': state => state.user.userInfo
    }),
    processStructure() {
      if (!this.processDetail) return [];
      return this.processDetail.process || [];
    }
  },
  watch: {
    /* 'applicationInfo.businessType': {
      handler(val) { // 业务类型为业务订单发票时显示订单信息
        this.showOrderInfo = val === 1;
      },
      immediate: true
    }, */
    'applicationInfo.isSign': {
      handler(val) { // 合同选择未签订时隐藏合同信息
        this.showContractInfo = val === 1;
      },
      immediate: true
    }
  },
  created() {
    this.createNew = Number(this.$route.query.createNew) || 0;// 再次发起（复制）
    const id = this.$route.params.id;
    const remodifyId = this.$route.query.remodifyId; // 修改
    const reapplyId = this.$route.query.reapplyId; // 重新申请
    this.remodifyId = remodifyId;
    this.reapplyId = reapplyId;
    if (id) {
      this.id = id;
      this.isEdit = true;
      this.getData();
      this.reapplyId && this.getExplanation();
    } else {
      this.isEdit = false;
      this.getExplanation();
    }
  },
  methods: {
    onSelectHistoryInvoice(data) {
      this.getData(data.referenceId, true);
    },
    getData(id = this.id, isSetHistoryData = false) {
      this.pageLoading = true;
      const params = { createNew: this.$route.query.createNew || 0 };
      getIssueInvoiceDetail(id, params).then(res => {
        if (res.code === 200) {
          this.financeData = res.data.financeTxnList || [];
          if (res.data.auditInfo && !this.reapplyId) {
            this.oldAuditInfo = Object.assign({}, res.data.auditInfo);
            this.auditInfo = JSON.parse(JSON.stringify(res.data.auditInfo));
            this.processDetail = JSON.parse(JSON.stringify(res.data.auditInfo));
          }
          isSetHistoryData && this.resetFormValidate();
          this.applicationInfo = res.data;
          // status 0：草稿中
          if (res.data.isDraft || !this.auditInfo || !this.auditInfo.id || this.reapplyId) {
            this.getExplanation();
          }
          this.$nextTick(() => {
            isSetHistoryData && this.$refs['applicationInfoRef'].setHistoryInvoice();
            res.data.proposerId && (this.$refs['applicationInfoRef'].defaultProposer = [{ id: res.data.proposerId, userName: res.data.proposer }]);
            this.$refs['orderInfoRef'] && this.$refs['orderInfoRef'].setTableData(res.data.orderInfo || []);
            this.$refs['contractInfoRef'] && this.$refs['contractInfoRef'].setContractInfo(res.data.contractInfo || []);
            this.pageLoading = false;
          });
          if (!isSetHistoryData) {
            this.version = Number(res.data.version) || 0;// 当前详情版本，version存在mixins
          }
        }
      }).catch(_ => {
        this.pageLoading = false;
      });
    },
    getProcess() {
      this.getProcessDetail(true);
      this.isRefresh = true;
    },
    // 重置校验提醒
    resetFormValidate() {
      this.$refs['applicationInfoRef'].resetFormValidate();
      this.$refs['orderInfoRef'] && this.$refs['orderInfoRef'].resetFormValidate();
    },
    openDrawer() { // 2.9.7 流程弹窗
      const promise = [];
      promise.push(this.$refs['applicationInfoRef'].validateForm());
      promise.push(this.$refs['taxpayerRef'].validateForm());
      this.$refs['orderInfoRef'] && promise.push(this.$refs['orderInfoRef'].validateForm());
      Promise.all(promise).then(res => { // 表单校验通过，则仅提交供应商表单部分，不提交流程信息，用来获取最新流程
        if (this.$refs['contractInfoRef']) {
          const contractIds = this.$refs['contractInfoRef'].getContractIds();
          if (!contractIds) {
            this.$message.warning('请设置合同信息');
            return;
          }
        }
        if (this.$refs['receiptInfoRef'] && this.financeData.length === 0) {
          this.$message.warning('请设置关联到账流水');
          return;
        }
        this.getProcessDetail();
        // 重新申请或者新建
      }).catch((err) => {
        console.log(err);
        ElMessage.warning('请检查信息是否填写完整');
      });
    },
    getExplanation() { // 获取审批说明
      processManagementDetail({ id: 3527, type: 15 }).then(res => {
        // 审批说明
        const data = res.data[0];
        this.explanationObj.content = data.explanation || '';
        this.explanationObj.styConfig = data.styConfig || '';
      }).catch(err => {
        console.log(err);
      });
    },
    // 获取订单所关联合同
    getOrderRelatedContract() {
      const orderInfo = this.$refs['orderInfoRef'].getOrderData() || {};
      const list = orderInfo.list || [];
      getOrderRelationContract({ orderInfo: list }).then(res => {
        this.$refs['contractInfoRef'].relationContract(res.data);
      });
    },
    // 获取流程详情
    getProcessDetail(isRefresh = false) {
      this.loading = true;
      const params = _.cloneDeep(this.applicationInfo);
      params.type = 15;
      // if (this.showOrderInfo) {
      //   const orderInfo = this.$refs['orderInfoRef'].getOrderData();
      //   params.orderTotalAmount = orderInfo.orderTotalAmount;
      //   params.orderInfo = orderInfo.list;
      // }

      // taxpayerType  0:公司  1:个人
      // 纳税人为公司时，到账流水的所有付款人必须与纳税人一致
      if (params.isArrival && this.$refs['receiptInfoRef'] && params.taxpayerType === 0) {
        const financeTxnList = this.$refs['receiptInfoRef'].tableData;
        if (financeTxnList && financeTxnList.length) {
          const isSame = financeTxnList.every(i => i.clientName === params.taxpayer && i.clientType === 0);
          if (!isSame) {
            showModal('您提交的审批单中纳税人名称与付款人名称不一致或公司/个人类型不统一，请重新填写。', '', {
              confirmButtonText: '确定',
              showCancelButton: false,
              type: 'warning',
              showClose: false,
              center: true,
              iconClass: 'charge-icon',
              customClass: 'del-message'
            }).then(() => {});
            return;
          }
        }
      }
      if (this.showContractInfo) {
        params.contractIds = this.$refs['contractInfoRef'].getContractIds();
      }
      if (this.applicationInfo.isArrival) {
        params.financeTxnIds = this.$refs['receiptInfoRef'].getIds();
      }
      formSubmitIssueInvoice(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          const data = res.data;
          if (this.remodifyId && !isRefresh) {
            this.isProcessChange(data, this.oldAuditInfo) && this.$refs['auditProcess'].setShowRefresh(true);
          } else {
            this.processDetail = data;
            this.auditInfo.activeTime = data.activationTime;
            this.auditInfo.id = data.id;
            // 创建人回填
            const proposer = {
              id: this.applicationInfo.proposerId,
              userName: this.applicationInfo.proposer
            };
            if (proposer.id === this.userInfo.id) {
              proposer.avatar = this.userInfo.avatar;
            }
            this.auditInfo.process = createAuditStructure(data.process, this.userInfo, proposer);
            this.auditInfo.senders = data.senderDiyUserList || [];
          }
          if (this.remodifyId && isRefresh) { // 修改刷新保存刷新后流程用于对比
            this.oldAuditInfo = Object.assign({}, data);
            this.oldAuditInfo.process.forEach(el => {
              this.oldAuditInfo.templateNodeId = el.id;
            });
            this.oldAuditInfo.activeTime = data.activationTime * 1000;
          }
          this.$refs['auditProcess'].openDrawer();
        } else {
          this.$message.error(res.message);
        }
      }).catch(_ => {
        this.loading = false;
      });
    },
    isProcessChange(nowAuditInfo = {}, oldAuditInfo = {}) {
      if (nowAuditInfo.activationTime !== (oldAuditInfo.activeTime / 1000)) {
        return true;
      }
      const nowProcessIds = nowAuditInfo && nowAuditInfo.process.map(el => el.id) || [];
      const oldProcessIds = oldAuditInfo && oldAuditInfo.process.map(el => el.templateNodeId) || [];
      return !isContained(nowProcessIds, oldProcessIds);
    },
    selectFinance(val) {
      this.financeData = val;
    },
    submit(submitType = SUBMITTYPE.SUBMIT, senders = []) { // 1草稿 2保存提交 3重新提交
      this.modifySenders = senders;// 存到mixins
      const params = _.cloneDeep(this.applicationInfo);
      params.submitType = submitType;
      params.isEditAudit = !!(this.remodifyId && this.isRefresh); // 修改时，流程被编辑或者更新
      params.auditInfo = this.auditInfo;
      /* if (this.showOrderInfo) {
        const orderInfo = this.$refs['orderInfoRef'].getOrderData();
        params.orderTotalAmount = orderInfo.orderTotalAmount;
        params.orderInfo = orderInfo.list;
      } */
      if (this.showContractInfo) {
        params.contractIds = this.$refs['contractInfoRef'].getContractIds();
      }
      if (this.applicationInfo.isArrival) {
        params.financeTxnIds = this.$refs['receiptInfoRef'].getIds();
      }
      if (this.isModifyForm) { // 节点修改走编辑的逻辑
        this.handleModifyData(params);
        this.edit(params);
        return;
      }
      const msg = submitType === SUBMITTYPE.DRAFT ? '请确认是否保存草稿' : '请确认是否发起审批';
      showModal(msg, '', {
        confirmButtonText: '确定', type: 'warning', showClose: false,
        center: true, iconClass: 'charge-icon', customClass: 'del-message del-message-cancel'
      }).then(() => {
        if (this.reapplyId || !this.isEdit) {
          this.add(params);
        } else {
          this.handleModifyData(params);
          this.edit(params);
        }
      });
      // 重新申请或者新建
    },
    add(params) {
      if (this.reapplyId && !this.createNew) params.submitType = 3;
      storeIssueInvoice(params).then(res => {
        if (res.code === 200) {
          ElMessage.success(params.submitType === SUBMITTYPE.DRAFT ? '保存成功' : '发起成功');
          if (res.data.id && res.data.processId) {
            this.$router.push({
              name: 'issueInvoiceDetail',
              query: {
                issueId: res.data.id,
                processId: res.data.processId
              }
            });
          } else {
            this.toBack();
          }
        } else {
          ElMessage.error(res.message);
        }
      }).catch(err => {
        if (err.code === 502) {
          this.$refs['auditProcess'].setShowRefresh(true);
        }
        this.loading = false;
      });
    },
    edit(params) {
      params.id = this.id;
      editIssueInvoice(params).then(res => {
        if (res.code === 200) {
          ElMessage.success(params.submitType === SUBMITTYPE.DRAFT ? '保存成功' : '发起成功');
          if (res.data.processId) {
            this.$router.push({
              name: 'issueInvoiceDetail',
              query: { issueId: params.id, processId: res.data.processId }
            });
          } else {
            this.toBack();
          }
        } else {
          ElMessage.error(res.message);
        }
      }).catch(err => {
        if (err.code === 502) {
          this.$refs['auditProcess'].setShowRefresh(true);
        }
        if (err.code === 505) { // 节点修改跳转详情
          this.nodeModifyJumpDetail({ routeName: 'issueInvoiceDetail', params: {}, query: { issueId: this.id, processId: this.remodifyId }});
        }
        this.loading = false;
      });
    },
    toBack() {
      this.$router.push({
        name: 'issueInvoice'
      });
    },
    handleDeleteReceipt(val) {
      showModal('确定删除该到账流水?', '', {
        iconClass: 'del-icon'
      }).then(() => {
        const index = this.financeData.findIndex(cur => { return cur.id === val; });
        this.financeData.splice(index, 1);
        // 到账流水列表删除后页数显示
        if (this.financeData.length >= 10) {
          const page = this.$refs.receiptInfoRef.page;
          const perPage = this.$refs.receiptInfoRef.perPage;
          const list = this.financeData.slice((page - 1) * perPage, page * perPage);
          if (list.length === 0 && page !== 1) {
            this.$refs.receiptInfoRef.page = this.$refs.receiptInfoRef.page - 1;
          }
        }
      }).catch(() => {
        return false;
      });
    },
    fillTaxpayerInfo(company) {
      this.$refs.taxpayerRef.receiptFillTax(company);
    }
  }
};
</script>

<style lang="scss" scoped>
.issue-invoice-create-container {
  margin: 16px;
  background-color: #fff;
  min-height: calc(100vh - 64px);
  &.mobile-create {
    // ::v-deep {
    //   .el-dropdown-menu__item {
    //     max-width: 200px;
    //   }
    // }
    .more-btn{
      width: 80px;
      height: 32px;
      padding: 0;
      font-size: 14px;
      margin-right: 12px;
    }
  }
}
::v-deep .pagination-flex {
  justify-content: center;
}
.page-container {
  padding: 24px 24px 0;
  &.pb55 {
    padding-bottom: 55px;
  }
  .bottom-btn-group {
    position: relative;
    width: auto;
    .bottom-checkbox {
      position: absolute;
      left: 0;
      transform: translate(-110%, 25%);
      ::v-deep .el-checkbox__label {
        font-size: 12px;
        padding-left: 4px;
      }
      ::v-deep .el-checkbox {
        color: #333;
      }
    }
  }
}
</style>
<style lang="scss">
.mobile-menu-invoice {
  &::v-deep {
    .el-dropdown-menu__item {
      font-size: 14px;
    }
  }
}
</style>
